package net.lcqf.http.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2021-2025 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2025/2/10 14:56
 * // +----------------------------------------------------------------------
 */

@Configuration
public class ThreadPoolConfig {

    /** 核心线程数 */
    private static final int CORE_POOL_SIZE = 20;

    /** 最大线程数 */
    private static final int MAX_POOL_SIZE = 60;

    /** 任务队列容量（阻塞队列） */
    private static final int QUEUE_CAPACITY = 380;

    /** 线程池维护线程所允许的空闲时间 */
    private static final int KEEP_ALIVE_SECONDS = 500;

    @Bean("taskExecutor")
    public ExecutorService executorService(){
        AtomicInteger c = new AtomicInteger(1);
        // 参考 https://www.cnblogs.com/fnlingnzb-learner/p/17621054.html
        LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(QUEUE_CAPACITY);
        return new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_SECONDS,
                TimeUnit.MILLISECONDS,
                queue,
                r -> new Thread(r, "web-" + c.getAndIncrement()),
                new RejectedExecution()
        );
    }

    public static class RejectedExecution implements RejectedExecutionHandler {
        private final Logger logger = LoggerFactory.getLogger(RejectedExecution.class);
        public RejectedExecution() {

        }
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            logger.error("任务[{}]被线程池[{}]拒绝执行，可能线程池已达到负载上限或线程池已经处于非运行态", r.toString(), executor.toString());
        }
    }
}
